package com.alex.wechat.mp.message.receive.controller;

import java.io.File;
import java.io.FileInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.cgform.common.CgAutoListConstant;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alex.wechat.mp.account.entity.WxAccountEntity;
import com.alex.wechat.mp.account.service.WxAccountServiceI;
import com.alex.wechat.mp.config.WxConsts;
import com.alex.wechat.mp.message.receive.entity.WxReceiveText;

import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;

/**
 * 文本消息收件箱
 * 
 */
@Controller
@RequestMapping("/wxReceiveTextController")
public class WxReceiveTextController {
  private static final Logger logger = LoggerFactory.getLogger(WxReceiveTextController.class);

  @Autowired
  private SystemService systemService;
  @Autowired
  private WxAccountServiceI weixinAccountService;
  @Autowired
  private WxMpService wxMpService;

  @RequestMapping(params = "list")
  public ModelAndView jumpList() {
    return new ModelAndView("com/gomore/wechat/mp/message/receive/receivetextlist");
  }

  @RequestMapping(params = "datagrid")
  @ResponseBody
  public void datagrid(WxReceiveText receiveText, HttpServletRequest request,
      HttpServletResponse response, DataGrid dataGrid) {

    CriteriaQuery cq = new CriteriaQuery(WxReceiveText.class, dataGrid);

    // cq.eq("toUserName", ResourceUtil.getSessionAccountId());
    WxAccountEntity WxAccountEntity = this.weixinAccountService.getWxAccountByLogin();
    if (WxAccountEntity != null) {
      cq.eq("accountId", WxAccountEntity.getId());
    }

    org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, receiveText);
    if (cq.getOrdermap().isEmpty()) {
      cq.addOrder("createDate", SortDirection.desc);
    }

    cq.add();
    this.systemService.getDataGridReturn(cq, true);
    TagUtil.datagrid(response, dataGrid);
  }

  @RequestMapping(params = "del")
  @ResponseBody
  public AjaxJson deleteSmsGroup(WxReceiveText receiveText, HttpServletRequest req) {
    AjaxJson j = new AjaxJson();
    receiveText = this.systemService.getEntity(WxReceiveText.class, receiveText.getId());

    this.systemService.delete(receiveText);

    String message = "删除信息数据成功！";
    systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
    j.setMsg(message);
    return j;
  }

  @RequestMapping(params = "jumpsendmessage")
  public ModelAndView responseMessage(HttpServletRequest req) {
    String id = req.getParameter("id");
    req.setAttribute("id", id);
    return new ModelAndView("com/gomore/wechat/mp/message/receive/messageinfo");
  }

  /**
   * 回复消息。
   * 
   * @param receiveText
   * @param req
   * @return
   */
  @RequestMapping(params = "reply")
  @ResponseBody
  public AjaxJson reply(WxReceiveText receiveText, HttpServletRequest req) {
    AjaxJson j = new AjaxJson();
    WxReceiveText oldMsg = this.systemService.getEntity(WxReceiveText.class, receiveText.getId());

    try {
      MyBeanUtils.copyBeanNotNull2Bean(receiveText, oldMsg);

      // TODO 多种回复方式： 回复客服消息
      WxMpKefuMessage kfTextMsg = WxMpKefuMessage.TEXT().toUser(oldMsg.getFromUserName())
          .content(receiveText.getRescontent()).build();
      // 简单回复文本消息
      wxMpService.getKefuService().sendKefuMessage(kfTextMsg);

      // 保存回复记录
      oldMsg.setRescontent(receiveText.getRescontent());
      oldMsg.setResponse(CgAutoListConstant.BOOL_TRUE);
      this.systemService.saveOrUpdate(oldMsg);
      systemService.addLog(receiveText.getRescontent(), Globals.Log_Type_UPDATE,
          Globals.Log_Leavel_INFO);
      j.setMsg("回复信息成功！");
    } catch (Exception e) {
      logger.error("", e);
      j.setMsg(e.getMessage());
      j.setSuccess(false);
    }
    return j;
  }

  /**
   * 通过媒体标识取得媒体。
   * 
   * @param req
   * @param resp
   * @throws Exception
   */
  @RequestMapping(params = "getMediaById")
  public void getMediaById(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    final String type = req.getParameter("type");
    final String mediaId = req.getParameter("id");

    if (WxConsts.XML_MSG_IMAGE.equals(type)) {
      resp.setContentType("image/jpeg;");
    } else if (WxConsts.XML_MSG_VOICE.equals(type)) {
      resp.setContentType("audio/amr;");
    } else if (WxConsts.XML_MSG_VIDEO.equals(type)) {
      resp.setContentType("video/mpeg4;");
    } else {
      // 默认不处理
    }
    File localFile = wxMpService.getMaterialService().mediaDownload(mediaId);
    resp.setHeader("Content-Length", String.valueOf(localFile.length()));
    resp.setHeader("Content-Disposition", "attachment; filename=\"" + localFile.getName() + "\"");
    IOUtils.copy(new FileInputStream(localFile), resp.getOutputStream());
  }

}